import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { TagServiceProxy, TagDto, CreateTagInput } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    selector: 'createOrEditTagModal',
    templateUrl: './create-or-edit-tag-modal.component.html',
    styles: []
})
export class CreateOrEditTagModalComponent extends AppComponentBase {

    @ViewChild('nameInput') nameInput: ElementRef;
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;       //
    // canChangeUserName = true;
    // isTwoFactorEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled');
    // isLockoutEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled');

    tag: TagDto;
    tags: TagDto[];

    constructor(
        injector: Injector,
        private _tagService: TagServiceProxy
    ) {
        super(injector);
        this.getTags();
    }

    getTags(): void {
        this._tagService.getTags().subscribe(result => this.tags = result.items);
    }


    show(tagId?: number): void {
        this.tag = new TagDto();
        if (!tagId) {
            this.active = true;
            this.modal.show();
        } else {
            this._tagService.get(tagId).subscribe(Result => {
                this.tag = Result;
                this.modal.show();
            });
        }

    }


    onShown(): void {
        this.active = true;
        // $(this.nameInput.nativeElement).focus();

        // this.organizationUnitTree.data = <IOrganizationUnitsTreeComponentData>{
        //     allOrganizationUnits: this.allOrganizationUnits,
        //     selectedOrganizationUnits: this.memberedOrganizationUnits
        // };
    }

    save(): void {
        let input = new CreateTagInput();
        input = this.tag;
        if (input.id === 0 || input.id === undefined) {
            this._tagService.create(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        } else {
            this._tagService.update(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        }
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}


